package util;

import java.sql.Clob;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.Date;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class JsonUtil {

	public static JSONArray formatRsToJsonArray(ResultSet rs) throws Exception {
		ResultSetMetaData md = rs.getMetaData();
		int num = md.getColumnCount();
		JSONArray array = new JSONArray();
		while (rs.next()) {
			JSONObject mapOfColValues = new JSONObject();
			for (int i = 1; i <= num; i++) {
				Object o = rs.getObject(i);
				if (o instanceof Date) {
					mapOfColValues.put(md.getColumnName(i), DateUtil.formatDate((Date) o, "yyyy-MM-dd"));
				} else {
					mapOfColValues.put(md.getColumnName(i), o);
				}
			}
			array.add(mapOfColValues);
		}
		return array;
	}

	public static JSONObject formatRsToJsonObject(ResultSet rs)
			throws Exception {
		ResultSetMetaData md = rs.getMetaData();
		int num = md.getColumnCount();
		JSONObject mapOfColValues = new JSONObject();
		while (rs.next()) {
			for (int i = 1; i <= num; i++) {
				Object o = rs.getObject(i);
				if (o instanceof Date) {
					mapOfColValues.put(md.getColumnName(i), DateUtil.formatDate((Date) o, "yyyy-MM-dd"));
				} else if (o instanceof Clob) {
					Clob clob = rs.getClob(i);
					String str = clob.getSubString((long) 1, (int) clob.length());
					mapOfColValues.put(md.getColumnName(i), str);
				} else {
					mapOfColValues.put(md.getColumnName(i), o);
				}
			}
		}
		return mapOfColValues;
	}
}
